using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using DevExpress.Xpo;
using DevExpress.XtraGrid.Views.Base;
using DevExpress.XtraGrid.Views.Grid.ViewInfo;
namespace ChuanPlus.FormControl
{
    public partial class ControlRejection : DevExpress.XtraEditors.XtraUserControl
    {
        Order order = null;
        List<RejectProduct> m_lstRejectProduct = new List<RejectProduct>();
        public ControlRejection()
        {
            InitializeComponent();
            gridBottom.DataSource = m_lstRejectProduct;
        }

        private void ButtonGo_Click(object sender, EventArgs e)
        {
            LoadData();
        }

        private void LoadData()
        {
            string orderID = textOrderID.Text;
            if (orderID != "")
            {
                order = ChuanPlus.DAO.OrderDAO.GetOrderByID(orderID);
                if (order != null)
                {
                    textRedInvNo.Text = order.RedInvNo;
                    textCustomer.Text = order.CustomerID.CustomerName;
                    textOrderDate.Text = order.OrderDate.ToString("MM/dd/yyyy");
                    textSalesRep.Text = order.SalesRep.AccountName;
                    textCommission.Text = order.CusCommission.ToString();
                    textPayment.Text = order.TOPayment;
                    gridTop.DataSource = order.OrderDetails;
                    m_lstRejectProduct.Clear();
                    gridBottom.RefreshDataSource();
                }
                else
                {
                    MessageBox.Show("Cannot found this PO No.","Message",MessageBoxButtons.OK,MessageBoxIcon.Information);
                }
            }
        }

        private void gridView1_CustomUnboundColumnData(object sender, DevExpress.XtraGrid.Views.Base.CustomColumnDataEventArgs e)
        {
            if (e.Column.FieldName == "Total" && e.IsGetData) e.Value =
            getTotalValue(sender as ColumnView, e.ListSourceRowIndex);
        }
        private decimal getTotalValue(ColumnView view, int listSourceRowIndex)
        {
            OrderDetails details = order.OrderDetails[listSourceRowIndex];
            return Convert.ToDecimal((details.UnitPrice * details.Quantity) + details.VAT);
        }

        private void gridView1_DoubleClick(object sender, EventArgs e)
        {
            // Checks whether an end-used has double clicked the row indicator.
            GridHitInfo hi = gridView1.CalcHitInfo(gridTop.PointToClient(MousePosition));
            if (!hi.InRow) return;
            // Retrieves the persistent object that corresponds to the currently focused grid row.
            int DSRowIndex = gridView1.Columns.View.GetDataSourceRowIndex(gridView1.FocusedRowHandle);
            OrderDetails detail = order.OrderDetails[DSRowIndex];
            RejectProduct rProduct = new RejectProduct(detail.StockID,detail.StockID.ID.ItemCode,detail.StockID.ID.Description,detail.UnitPrice,detail.Quantity);
            if (m_lstRejectProduct.Contains(rProduct))  // do not add duplicate product
                return;
            m_lstRejectProduct.Add(rProduct);
            gridBottom.RefreshDataSource();
        }

        private void gridView2_ValidatingEditor(object sender, DevExpress.XtraEditors.Controls.BaseContainerValidateEditorEventArgs e)
        {
            if (gridView2.FocusedColumn.FieldName == "Qty")
            {

                int DSRowIndex = gridView2.Columns.View.GetDataSourceRowIndex(gridView2.FocusedRowHandle);

                double instock = m_lstRejectProduct[DSRowIndex].Qty;
                //Get the currently edited value
                double qty = Convert.ToDouble(e.Value);
                //Specify validation criteria
                if (qty < 0)
                {
                    e.Valid = false;
                    e.ErrorText = "Enter a positive value";
                }
                if (qty > instock)
                {
                    e.Valid = false;
                    e.ErrorText = "Reduce the quantity (" + instock + " is maximum)";
                }
            }
            if (gridView2.FocusedColumn.FieldName == "UnitPrice")
            {
                if (Convert.ToDouble(e.Value) < 0)
                {
                    e.Valid = false;
                    e.ErrorText = "Enter a positive value";
                }
            }
        }

        private void gridView2_CellValueChanged(object sender, CellValueChangedEventArgs e)
        {
            int DSRowIndex = gridView2.Columns.View.GetDataSourceRowIndex(e.RowHandle);
            if (e.Column.FieldName == "Quantity")
                m_lstRejectProduct[DSRowIndex].Qty = Double.Parse(e.Value.ToString());
            else if (e.Column.FieldName == "UnitPrice")
                m_lstRejectProduct[DSRowIndex].UnitPrice = Double.Parse(e.Value.ToString());
            m_lstRejectProduct[DSRowIndex].RefreshTotal();
            gridBottom.RefreshDataSource();     
        }

        private void gridView2_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete)
            {
                // Retrieves the persistent object that corresponds to the currently focused grid row.
                int DSRowIndex = gridView2.Columns.View.GetDataSourceRowIndex(gridView2.FocusedRowHandle);
                m_lstRejectProduct.RemoveAt(DSRowIndex);     // do not add to list if product is added      
                gridBottom.RefreshDataSource();
            }
        }

        private void buttonReset_Click(object sender, EventArgs e)
        {
            Reset();
        }

        private void Reset()
        {               
            m_lstRejectProduct.Clear();
            gridBottom.RefreshDataSource();
            dateReject.Text = "";
            memoReason.Text = "";
        }

        private void ButtonReject_Click(object sender, EventArgs e)
        {
            if (!FormValidation()) return;
            DialogResult result =  MessageBox.Show("Are you sure want to create a new Rejection", "Confirm", MessageBoxButtons.YesNo, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
            if (result.ToString() == "Yes")
            {
                // get summary value from footer row
                double total = Convert.ToDouble(gridView2.Columns["Total"].SummaryItem.SummaryValue);
                Rejection rejection = new Rejection(dateReject.DateTime,order,total,memoReason.Text,total,null,"H");
                foreach (RejectProduct item in m_lstRejectProduct)
                {
                    RejectionDetails details = new RejectionDetails(item.stock, item.Qty, item.UnitPrice,item.Tax);
                    rejection.RejectionDetails.Add(details);
                }
                rejection.Save();
                Reset();
                           
            }
        }
        private bool FormValidation()
        {
            if (dateReject.Text == "")
            {
                MessageBox.Show("Please select reject date","Message");
                return false;
            }
            if (m_lstRejectProduct.Count == 0)
            {
                MessageBox.Show("Please select product to reject","Message");
                return false;
            }
            return true;
        }

        private void textOrderID_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                LoadData();
            }
        }
    }
    public class RejectProduct
    {
        private Stock _Stock;
        public Stock stock
        {
            get { return _Stock; }
            set { _Stock = value; }
        }
        private string _ItemCode;
        public string ItemCode
        {
            get { return _ItemCode; }
            set { _ItemCode = value; }
        }
        private string _Description;
        public string Description
        {
            get { return _Description; }
            set { _Description = value; }
        }
        private double _UnitPrice;
        public double UnitPrice
        {
            get { return _UnitPrice; }
            set
            {
                _UnitPrice = value;
                _total = Qty * UnitPrice;
            }
        }
        private double _Tax;
        public double Tax
        {
            get { return _Tax; }
            set { _Tax = value; }
        }
        private double _Qty;
        public double Qty
        {
            get { return _Qty; }
            set
            {
                _Qty = value;
                _total = Qty * UnitPrice;
            }
        }
        private double _total;
        public double Total
        {
            get { return _total; }
            set { _total = value; }
        }
        public override bool Equals(Object b)
        {
            bool result = true;
            if (b == null) result = false;
            try
            {
                RejectProduct p = (RejectProduct)b;
                if (p.stock.ID.ID == this.stock.ID.ID)
                    result = true;
                else
                    result = false;
            }
            catch
            {
                result = false;
            }
            return result;
        }
        public override int GetHashCode()
        {
            return base.GetHashCode();
        }
        public void RefreshTotal()
        {     
       
               Tax = (Qty * UnitPrice * stock.ID.Tax) / 100;
               _total = _total + Tax;           
        }
        /// <summary>
        /// Initializes a new instance of the RejectProduct class.
        /// </summary>
        /// <param name="stock"></param>
        /// <param name="itemCode"></param>
        /// <param name="description"></param>
        /// <param name="unitPrice"></param>
        /// <param name="qty"></param>
        public RejectProduct(Stock stock, string itemCode, string description, double unitPrice, double qty)
        {
            _Stock = stock;
            _ItemCode = itemCode;
            _Description = description;
            _UnitPrice = unitPrice;
            _Qty = qty;
            RefreshTotal();
        }
    }
}
